package com.zx.cloud.file.service.impl;

import com.zx.cloud.file.service.FileUploadService;
import com.zx.cloud.common.config.FileProperties;
import com.zx.cloud.file.service.dto.FileDto;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.zx.cloud.common.utils.FileUtil;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLDecoder;

/**
 *
 */
@Service
public class FileServiceImpl implements FileUploadService {
    @Value("${file.uri}")
    private String fileUri;
    private final FileProperties properties;
    public FileServiceImpl(   FileProperties properties) {
        this.properties = properties;
    }
    @Override
    public FileDto upload(MultipartFile multipartFile) {
       File file = FileUtil.upload(multipartFile, properties.getPath().getPath());
       assert file != null;
       return new FileDto(fileUri, file.getName());

    }

    @Override
    public void fileDown(String uriPath, HttpServletResponse response) {
        if (org.springframework.util.StringUtils.isEmpty(uriPath)) {
            return;
        }

        try {
            uriPath= URLDecoder.decode(uriPath,"utf-8");
            System.out.println(uriPath);
            System.out.println(uriPath.substring(uriPath.lastIndexOf(File.separator)+1));
            StringBuffer sbn = new StringBuffer();
            sbn.append(properties.getPath().getPath()).append(uriPath);
            String dirFile = sbn.toString();
            String fileType = uriPath.substring(uriPath.indexOf('.') + 1);
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.addHeader("Content-Disposition","inline; filename="+uriPath.substring(uriPath.lastIndexOf(File.separator)+1));
            response.setHeader("Pragma", "no-cache");
            response.setContentType("file/" + fileType);

            ServletOutputStream out = response.getOutputStream();

            File file = new File(dirFile);
            if (!file.exists()) {
                return;
            }
            FileInputStream in = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            in.close();
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }
}
